package com.alice.consumer.controller;

import com.alice.consumer.pojo.Item;
import com.alice.consumer.utils.Result;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by caoxuel on 2020/9/23 10:15
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {
    Logger logger = LoggerFactory.getLogger(ConsumerController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

//    方式一
//    @GetMapping("{id}")
//    public Result queryById(@PathVariable Integer id){
//        String url = "http://localhost:9091/item/"+id;
//        return restTemplate.getForObject(url,Result.class);
//    }

    /**
     * 方式二：通过eureka获取注册的user-service实例列表
     * @param id
     * @return
     */
//    @GetMapping("{id}")
//    public Result queryById(@PathVariable Integer id) {
//        List<ServiceInstance> instances = discoveryClient.getInstances("item-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/item/" + id;
//        return restTemplate.getForObject(url, Result.class);
//    }

    // 方式三
    @GetMapping("{id}")
    //@HystrixCommand(fallbackMethod = "queryByIdFallback")
    @HystrixCommand
    public String queryById(@PathVariable Integer id) {
        String url = "http://item-service/item/" + id;
        return restTemplate.getForObject(url, String.class);
    }

    public String queryByIdFallback(Integer id){
        logger.error("查询商品信息失败。id: {}",id);
        return "网络拥挤";
    }

    public String defaultFallback(Integer id){
        return "默认提示：网络拥挤";
    }
}
